package com.example.app_back.service;

import com.example.app_back.convert.UserConverter;
import com.example.app_back.dao.User;
import com.example.app_back.dao.UserRepository;
import com.example.app_back.dto.AddUserDto;
import com.example.app_back.dto.GetUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
     @Autowired
     private UserRepository userRepository;
    @Override
    public GetUserDto getUserById(long id) {
        User user= userRepository.findById(id).orElseThrow(RuntimeException::new);
       return UserConverter.convertUser(user);
    }

    @Override
    public Long addNewUser(AddUserDto adduserdto) {
      List<User> userList=  userRepository.findByUserName(adduserdto.getName());
      if(!CollectionUtils.isEmpty(userList)){
          throw new IllegalStateException("用户名被占用");
      }
      User user =userRepository.save(UserConverter.convertUser(adduserdto));
        return user.getId();
    }
    @Override
    public void deleteUserById(long id){
        userRepository.findById(id).orElseThrow(()->new IllegalArgumentException("用户不存在"));
        userRepository.deleteById(id);
    }

    @Override
    public GetUserDto updateUserById(long id, String name, String password){
        User userInDB = userRepository.findById(id).orElseThrow(()->new IllegalArgumentException("用户不存在"));
       if(StringUtils.hasLength(name)&&!userInDB.getUserName().equals(name)){
           System.out.println(name);
           userInDB.setUserName(name);
       }
       if(StringUtils.hasLength(password)&&!userInDB.getPassword().equals(password)){
           userInDB.setPassword(password);
       }
      User user= userRepository.save(userInDB);
       return UserConverter.convertUser(user);
    }
}
